/*
 * @(#)KeywordController.java $version 2012. 1. 24.
 *
 */

package com.mywep.myalimi.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.mywep.myalimi.model.User;
import com.mywep.myalimi.model.UserKeyword;
import com.mywep.myalimi.service.ContentsService;
import com.mywep.myalimi.service.UserKeywordService;

/**
 * @author 한지웅
 */
@Controller
@RequestMapping("/alimi/keyword")
public class UserKeywordController {
	@Autowired
	private UserKeywordService userKeywordService;
	@Autowired
	private ContentsService contentsService;

	@RequestMapping(value = "/get.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView getKeywords(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		User user = (User)request.getAttribute("user");

		if (userKeywordService.getTotalCountKeywords(user.getId()) <= 0) {
			mav.setViewName("keyword/empty");
			return mav;
		}
		List<UserKeyword> userKeywords = userKeywordService.getKeywords(user.getId());
		for (UserKeyword userKeyword : userKeywords) {
			userKeyword.setNewContentCount(contentsService.newContentsCount(user, userKeyword.getKeyword()));
			userKeyword.setUserContentCount(contentsService.userContentsCount(user, userKeyword.getKeyword()));
		}

		mav.addObject("userKeywords", userKeywords);
		mav.setViewName("keyword/list");
		return mav;
	}

	@RequestMapping(value = "/add.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView addKeyword(HttpServletRequest request, String keyword) {
		ModelAndView mav = new ModelAndView();
		User user = (User)request.getAttribute("user");
		userKeywordService.txAddKeyword(user, keyword);
		RedirectView rv = new RedirectView("/alimi/keyword/get.alm");
		mav.setView(rv);
		return mav;
	}


	@RequestMapping(value = "/delete.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView deleteKeywordKeyword(HttpServletRequest request, int userKeywordKey, String keyword) {
		ModelAndView mav = new ModelAndView();
		User user = (User)request.getAttribute("user");
		userKeywordService.txDeleteKeyword(user, userKeywordKey, keyword);
		RedirectView rv = new RedirectView("/alimi/keyword/get.alm");
		mav.setView(rv);
		return mav;
	}

}
